﻿using BLL;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Model;
using System.ComponentModel;
using TiboShop.Models;

namespace TiboShop.Controllers
{
    public class LoginController : Controller
    {
        //注入BLLUser服务
        private readonly BLLUser bllUser;
        private readonly IDistributedCache distributed;
        private readonly ISession _session;
        private readonly IHttpContextAccessor _contextAccessor;
        public LoginController(BLLUser bllUser, IDistributedCache _distributed,IHttpContextAccessor httpContext)
        {
            _contextAccessor = httpContext;
            this.bllUser = bllUser;
            this.distributed = _distributed;
            _session = _contextAccessor.HttpContext.Session;
        }

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string name, string password)
        {
            Console.WriteLine(name+password);
            User user = new();
            user = bllUser.Login(name, password)!;
            if (user!=null)
            {
                
                //Session中保存用户信息
                _session.SetInt32("UID",user.ID);
                _session.SetInt32("URID",user.role.ID);
                _session.SetString("UNAME",user.Name);
                _session.SetString("UTELEPHONE", user.Telephone);
                
                return RedirectToAction("Index", "Mall");
            }
            MessageBoxVO messageBoxVO = new MessageBoxVO();
            messageBoxVO.Msg = "账号或密码错误，请从新登录！";
            messageBoxVO.RedrectUrl = "Index";
            return View("Views\\Shared\\Components\\MessageBox\\Default.cshtml", messageBoxVO);
        }
        [HttpPost]
        public ActionResult SignUp(string name, string telephone, int urole, string password)
        {
            
            User user = new();
            if ((user = bllUser.SignUp(name, telephone, urole, password)) != null)
            {

                //注册成功就登录
                //Session中保存用户信息
                _session.SetInt32("UID", user.ID);
                _session.SetInt32("URID", user.role.ID);
                _session.SetString("UNAME", user.Name);
                _session.SetString("UTELEPHONE", user.Telephone);

                return RedirectToAction("Index", "Mall");
            }
            else
            {
                return RedirectToAction("index");
            }    
            //注册失败返回登录

        }
      
    }
}
